/*
 * _1w.c
 *
 * Created: 28.02.2013 14:44:08
 *  Author: saenko
 */ 
#include <avr/io.h>

#define OW_PORT PORTD
#define OW_DDR  DDRD
#define OW_INPORT  PIND
#define OW_PIN PD2

#define FCPU 8000000

#define cbi(reg,bit)	reg &= ~(_BV(bit))
#define sbi(reg,bit)	reg |= (_BV(bit))

#define OW_PULL_DOWN cbi(OW_PORT,OW_PIN);sbi(OW_DDR,OW_PIN)
#define OW_PULL_UP	 cbi(OW_PORT,OW_PIN);cbi(OW_DDR,OW_PIN)

#define OW_IN bit_is_set(OW_INPORT,OW_PIN)

uint8_t ow_buf[16];

void ow_delay_15_us(uint8_t cycles) //1:15; 2:30; 3:45; 32: 480
{
	for(uint8_t j = 0; j<cycles; j++)
	{
		for(uint8_t i = 0; i<27; i++)
		{
			asm("nop");
		}
	}	
}

void ow_short_delay(void) //1:15; 2:30; 3:45; 32: 480
{

		for(uint8_t i = 0; i<8; i++)
		{
			asm("nop");
		}

}

void OW_init(void)
{
	cbi(OW_DDR,OW_PIN);
}

uint8_t OW_reset(void)
{
	uint8_t temp;
	
	OW_PULL_DOWN;
	ow_delay_15_us(35);
	OW_PULL_UP;
	
	ow_delay_15_us(6);
	
	if(OW_IN) temp = 1;
	else temp = 0;
	
	ow_delay_15_us(10);
	
	return temp;
}

void OW_OUT_1(void)
{
		OW_PULL_DOWN;
		ow_short_delay();
		OW_PULL_UP;
		ow_delay_15_us(3);
}

void OW_OUT_0(void)
{
	OW_PULL_DOWN;
	ow_short_delay();
	ow_delay_15_us(3);
	OW_PULL_UP;	
}

void OW_OUT_BYTE(uint8_t byte)
{
	for(uint8_t i = 0; i<8; i++)
	{
		if(bit_is_set(byte,i)) OW_OUT_1();
		else OW_OUT_0();
	}
	ow_short_delay();
}

uint8_t OW_READ_BIT(void)
{
	uint8_t temp;
	
	OW_PULL_DOWN;
	ow_short_delay();
	OW_PULL_UP;
	ow_delay_15_us(2);
	
	if (OW_IN) temp = 1;
	else temp = 0;
	
	ow_delay_15_us(2);	
	
	return temp;	
}

uint8_t OW_READ_BYTE(void)
{
	uint8_t temp;
	
	for(uint8_t i = 0; i<8 ; i++)
	{
		if(OW_READ_BIT()) sbi(temp,i);
		else cbi(temp,i);
	}
	
	return temp;
}

void OW_READ_ARRAY(uint8_t num)
{
	for(uint8_t i = 0; i < num; i++) ow_buf[i] = OW_READ_BYTE();	
}


void OW_OUT_ARRAY(uint8_t *arr, uint8_t num)
{
	for(uint8_t i = 0; i < num; i++) OW_OUT_BYTE(arr[i]);
}

//************************************************************************


